import React, {useEffect, useState} from 'react';
import {Table, Button, Modal, Form, Input, Space, message, Input as AntInput} from 'antd';
import {
    addAcademyInfo,
    batchDeleteAcademyInfo,
    deleteAcademyInfo,
    getAcademyInfo,
    updateAcademyInfo
} from "../../api/academy.js";

const AcademyPage = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingRecord, setEditingRecord] = useState(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [searchKeyword, setSearchKeyword] = useState('');

    useEffect(() => {
        fetchAcademyInfo();
    }, []);
    const fetchAcademyInfo = async () => {
        setLoading(true);
        try {
            const res = await getAcademyInfo(null);
            setData(res.data);
        } catch (error) {
            message.error('获取学院列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    // 获取当前选中的记录
    const selectedRecords = data.filter(item => selectedRowKeys.includes(item.id));

    // ========== 表格配置 ==========
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, record, index) => index + 1,
        },
        {
            title: '学院名称',
            dataIndex: 'academyName',
            align: 'center',
            key: 'academyName'
        },
        {
            title: '学院代码',
            dataIndex: 'academyCode',
            align: 'center',
            key: 'academyCode'
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
                    <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
                </Space>
            )
        }
    ];

    // ========== 操作方法 ==========
    const handleDelete = (id) => {
        Modal.confirm({
            title: '确认删除该学院信息？',
            okText: "确认",
            cancelText: "取消",
            onOk: () => {
                deleteAcademy({academyId: id});
            }
        });
    };

    const handleBatchDelete = () => {
        Modal.confirm({
            title: '确认删除选中的学院信息？',
            okText: "确认",
            cancelText: "取消",
            onOk: () => {
                batchDeleteAcademy({
                    ids: selectedRowKeys
                })
            }
        });
    };

    const handleEdit = (record) => {
        setEditingRecord(record);
        form.setFieldsValue(record);
        setIsModalVisible(true);
    };

    const handleAdd = () => {
        setEditingRecord(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const handleOk = () => {
        form.validateFields().then(values => {
            if (editingRecord) {
                setData(data.map(item =>
                    item.id === editingRecord.id ? {...item, ...values} : item
                ));
                updateAcademy({
                    id: editingRecord.id,
                    academyName: values.academyName,
                    academyCode: values.academyCode
                });
            } else {
                addAcademy(values);
            }

            setIsModalVisible(false);
            form.resetFields();
        }).catch(error => {
            console.log('表单验证失败:', error);
        });
    };
    const addAcademy = async (data) => {
        try {
            const res = await addAcademyInfo(data);
            if (res.code === 200) {
                message.success("新增成功")
                fetchAcademyInfo();
            }
        } catch (error) {
            message.error('新增学院列表失败');
            console.error(error);
        }
    }
    const updateAcademy = async (data) => {
        try {
            const res = await updateAcademyInfo(data);
            if (res.code === 200) {
                message.success("修改成功")
                fetchAcademyInfo();
            }
        } catch (error) {
            message.error('修改学院信息失败');
            console.error(error);
        }
    }
    const deleteAcademy = async (data) => {
        try {
            const res = await deleteAcademyInfo(data);
            if (res.code === 200) {
                message.success("删除成功")
                fetchAcademyInfo();
            }
        } catch (error) {
            message.error('删除学院信息失败');
            console.error(error);
        }
    }
    const batchDeleteAcademy = async (data) => {
        try {
            const res = await batchDeleteAcademyInfo(data);
            if (res.code === 200) {
                message.success("批量删除成功")
                fetchAcademyInfo();
                setSelectedRowKeys([]);
            }
        } catch (error) {
            message.error('批量删除学院信息失败');
            console.error(error);
        }
    }

    const handleCancel = () => {
        setIsModalVisible(false);
        form.resetFields();
    };

    const handleSearch = async () => {
        if (!searchKeyword.trim()) {
            message.warning('请输入搜索内容');
            return;
        }

        setLoading(true);
        try {
            const res = await getAcademyInfo(searchKeyword);
            setData(res.data);
        } catch (error) {
            message.error('获取学院列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleInputChange = (e) => {
        if (e.target.value === '') {
            fetchAcademyInfo();
        }
        setSearchKeyword(e.target.value);
    };
    return (
        <div style={{padding: 14}}>
            <div style={{marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8}}>
                <Space>
                    <Button type="primary" onClick={handleAdd}>新增学院</Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>批量删除</Button>
                </Space>

                <Space>
                    <Input.Search
                        placeholder="请输入学院名称"
                        value={searchKeyword}
                        onChange={handleInputChange}
                        onSearch={handleSearch}
                        style={{width: 250}}
                        allowClear
                    />
                </Space>
            </div>

            <Table
                rowKey="id"
                dataSource={data}
                columns={columns}
                rowSelection={rowSelection}
                loading={loading}
            />

            <Modal
                title={editingRecord ? '编辑学院信息' : '新增学院信息'}
                open={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                okText={editingRecord ? "更新" : "新增"}
                cancelText="取消"
            >
                <Form form={form} layout="vertical" name="academy_form">
                    <Form.Item
                        label="学院名称"
                        name="academyName"
                        rules={[
                            { required: true, message: '请输入学院名称' },
                            { whitespace: true, message: '名称不能为空白字符' },
                            { max: 50, message: '名称长度不能超过50个字符' }
                        ]}
                    >
                        <Input placeholder="请输入学院名称"/>
                    </Form.Item>

                    <Form.Item
                        label="学院代码"
                        name="academyCode"
                        rules={[
                            { required: true, message: '请输入学院代码' },
                            {
                                pattern: /^[0-9]{2}$/,
                                message: '学院代码必须是两位数字，如：01、10'
                            },
                            { len: 2, message: '必须输入两位数字' }
                        ]}
                    >
                        <Input placeholder="请输入两位数字，如：01、10"/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default AcademyPage;